const Koa = require('koa')
const bodyParser = require('koa-bodyparser')
const Router = require('koa-router')
const cors = require('koa2-cors')
const { connectDb, initSchema } = require('./datebase/init.js')

connectDb()
initSchema()
const app = new Koa()

// 解决跨域
app.use(cors({
  credentials: true, // 跨域和传递cookie
  // origin: 'http://localhost:8082',
  origin: 'https://118.25.208.36' // 这里使用ip，不能使用域名
}))
app.use(bodyParser())

// 请求之前进行接口鉴权
app.use(async (ctx, next) => {
  const { url } = ctx.request
if (url !== '/cs_editor/user/login' && url !== '/cs_editor/user/register' && url !== '/cs_editor/user/captcha') {
    // 不是首页
    if (!ctx.cookies.get('name')) {
      ctx.body = {
        code: 401, // 未登录或者登录过期
        message: '您还未登录或者登录期已过，请重新登录'
      }
    } else {
      //必须搭配异步，使用await next往下继续执行
      await next()
    }
  } else {
    await next()
  }
})

const router = new Router()
const UserRouter = require('./datebase/api/user')
const ArticleRouter = require('./datebase/api/article')
router.use('/cs_editor/user', UserRouter.routes())
router.use('/cs_editor/article', ArticleRouter.routes())
app.use(router.routes()).use(router.allowedMethods())

app.listen(3000, () => {
  console.log('server running is %s', 3000);
})